﻿/* ######################################## *\
 * ### Copyright (C) 2009 AJ Ravindiran ### *
\* ######################################## */
using System;
using System.Net.Sockets;
using System.Collections.Generic;

using AJRavindiran.Jolt.Utilities;
using AJRavindiran.Jolt.RuneScape.Models.Characters;

namespace AJRavindiran.Jolt.RuneScape.Models
{
    /// <summary>
    /// Represents a manager for all character related content.
    /// </summary>
    public class CharacterManager
    {
        #region Fields
        private Dictionary<int, Character> characters;
        #endregion Fields

        #region Properties
        #endregion Properties

        #region Constructors
        /// <summary>
        /// Constructs a new character manager.
        /// </summary>
        public CharacterManager()
        {
            Jolt.GetLog().WriteInfo("Constructing character manager...");
            characters = new Dictionary<int, Character>();
        }
        #endregion Constructors

        #region Methods
        /// <summary>
        /// Register a new player, and add him into the current characters list.
        /// </summary>
        public void Register(Character character)
        {
            characters.Add(character.GetDetails().ConnectionId, character);
        }

        /// <summary>
        /// Unregister a player.
        /// </summary>
        public void UnRegister(Character character)
        {
            if (character.GetStatus().Online)
                RuneScape.GetAccountManager().SaveCharacter(character);

            Jolt.GetTcpConnection().FreeConnection(character.GetDetails().ConnectionId);
            character.Destroy();
            characters.Remove(character.GetDetails().ConnectionId);
        }

        public bool IsOnline(string name, Character character)
        {
            foreach (Character c in characters.Values)
            {
                if (character.GetDetails().ConnectionId != c.GetDetails().ConnectionId)
                {
                    if (c.GetDetails().Username.EqualsIgnoreCase(name))
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// Accessor for the list of characters.
        /// </summary>
        public Dictionary<int, Character> GetCharacters()
        {
            return characters;
        }
        #endregion Methods
    }
}
